package com.kevinwu.framework.servlet;

import com.kevinwu.framework.annotations.*;
import com.kevinwu.framework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义mvc核心类 拦截分发等等 KvDispatcherServlet
 */
public class KvDispatcherServlet extends HttpServlet {

    //自定义mvc配置文件
    private Properties properties = new Properties();
    //缓存扫描到的类的全限定类名
    private List<String> classNames = new ArrayList<>();
    //ioc容器
    private Map<String,Object> ioc = new HashMap<String,Object>();
    //拦截器链
    private Map<String,Object> interceptors = new HashMap<String,Object>();
    // handlerMapping 映射器
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {

        // 1 读取web.xml配置文件中的参数 加载配置文件 kevinmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        // 2 扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));

        // 3 初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        // 4 实现依赖注入
        doAutoWired();

        // 5 构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

    }

    // 加载配置文件kevinmvc.properties
    private void doLoadConfig(String contextConfigLocation) {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // kevinmvc.properties配置文件中配置的scanPackage: com.kevinwu.kevinwudemo
    private void doScan(String scanPackage) {

        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();

        for(File file: files) {
            if(file.isDirectory()) {
                // 递归
                doScan(scanPackage + "." + file.getName());
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    // 基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
    private void doInstance()  {

        if(classNames.size() == 0) return;

        try{

            for (int i = 0; i < classNames.size(); i++) {

                String className =  classNames.get(i);
                Class<?> aClass = Class.forName(className);

                if(aClass.isAnnotationPresent(KevinController.class)) {

                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName,o);

                }else if(aClass.isAnnotationPresent(KevinService.class)) {

                    KevinService annotation = aClass.getAnnotation(KevinService.class);
                    String beanName = annotation.value();
                    // 如果指定了id，就以指定的为准
                    if(!"".equals(beanName.trim())) {
                        ioc.put(beanName,aClass.newInstance());
                    }else{
                        // 如果没有指定，就以类名首字母小写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.newInstance());
                    }
                    // service再以接口名为id，放入一份对象到ioc中，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以接口的全限定类名作为id放入
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }

                }else if(aClass.isAnnotationPresent(KevinInterceptor.class)){//拦截器链
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    interceptors.put(lowerFirstSimpleName,o);
                }else{
                    continue;
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  实现依赖注入
    private void doAutoWired() {

        if(ioc.isEmpty()) {return;}
        // 遍历ioc中所有对象，查看对象中的字段，是否有@KevinAutowired注解，如果有维护依赖注入关系
        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            // 获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {

                Field declaredField = declaredFields[i];
                if(!declaredField.isAnnotationPresent(KevinAutowired.class)) {
                    continue;
                }
                KevinAutowired annotation = declaredField.getAnnotation(KevinAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())) {
                    // 没有配置具体的bean id，根据当前字段类型注入（接口注入）
                    beanName = declaredField.getType().getName();
                }
                // 开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //构造一个HandlerMapping处理器映射器
    private void initHandlerMapping() {

        if(ioc.isEmpty()) {return;}

        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            // 获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(KevinController.class)) {continue;}
            String baseUrl = "";
            if(aClass.isAnnotationPresent(KevinRequestMapping.class)) {
                KevinRequestMapping annotation = aClass.getAnnotation(KevinRequestMapping.class);
                baseUrl = annotation.value(); //Controller类上的路径配置
            }

            // 获取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                //  方法没有标识KevinRequestMapping不处理
                if(!method.isAnnotationPresent(KevinRequestMapping.class)) {continue;}

                KevinRequestMapping annotation = method.getAnnotation(KevinRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;
                // 把method所有信息及url封装为一个Handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));

                //方法参数处理
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {

                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),j);
                    }
                }

                // 建立url和method之间的映射关系（map缓存起来）
                handlerMapping.add(handler);
            }
        }
    }

    /**
     * 重写父类的doGet方法，指向doPost方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    /**
     * 重写父类的doPost方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 根据uri获取到能够处理当前请求的hanlder
        Handler handler = getHandler(req);
        if("/favicon.ico".equals(req.getRequestURI())){
            return;
        }
        System.out.println("URL:"+req.getRequestURI());
        if(handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        // 获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
        Object[] paraValues = new Object[parameterTypes.length];
        // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 遍历request中所有参数  （填充除了request，response之外的参数）
        for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {

            String value = StringUtils.join(param.getValue(), ",");
            // 如果参数和方法中的参数匹配上了，填充数据
            if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}
            // 方法形参确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            //把前台传递过来的参数值填充到对应的位置去
            paraValues[index] = value;
        }

        //填充HttpServletRequest参数
        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;
        //填充HttpServletResponse参数
        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
        paraValues[responseIndex] = resp;
        // 最终调用handler的method属性
        try {
            //执行拦截器链的perHander方法
            // 方法体包含KevinSecurity注解并且拦截器链不为空
            if(handler.getMethod().isAnnotationPresent(KevinSecurity.class) && !interceptors.isEmpty()){
                KevinSecurity annotation = handler.getMethod().getAnnotation(KevinSecurity.class);
                String[] username = annotation.value();

                for(Map.Entry<String,Object> entry: interceptors.entrySet()){
                    Class<?> aClass = entry.getValue().getClass();
                    Method perHander = aClass.getMethod("perHander",String[].class,String.class);
                    boolean invoke = (boolean) perHander.invoke(entry.getValue(),new Object[]{username,(String) paraValues[2]});
                    if(invoke){
                        throw  new RuntimeException("没有权限访问");
                    }
                }
            }
            //调用handler的原方法执行
            String message = (String) handler.getMethod().invoke(handler.getController(), paraValues);
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(message);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (RuntimeException e){
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(e.getMessage());
            return;
        }
    }

    /**
     * 根据请求获取url对应的handler处理器
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {

        if(handlerMapping.isEmpty()){return null;}
        String url = req.getRequestURI();
        for(Handler handler: handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }

    /**
     * 首字母小写处理工具方法
     * @param str
     * @return
     */
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

}
